package com.gotkicry.foodmenu;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Enzo Cotter on 2019/5/27.
 */
public class ShowFragment extends Fragment {
    private static final String TAG = "ShowFragment";
    ListView listView;
    private List<Map> list;
    MyAdapter adapter;
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_show, container, false);
        initView(view);
        //Log.d(TAG, "onCreateView: "+savedInstanceState.containsKey("cid"));
        Bundle bundle = getArguments();
        if(bundle.containsKey("cid")){
            int cid = bundle.getInt("cid");
            initData(cid);
        }else{
            initData((int)(Math.random()*359));
        }


        return view;
    }

    private void initView(View view) {
        listView = view.findViewById(R.id.list);
        list = new ArrayList<>();
        adapter = new MyAdapter(list);
        listView.setAdapter(adapter);
    }

    private void initData(int cid) {
        String url = "https://apis.juhe.cn/cook/index?key=4c418590b697b3860fd06132a2cdfe2f&cid="+cid;
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d(TAG, "onResponse: "+jsonObject);
                if(jsonObject.optString("reason").equals("Success")){
                    JSONObject jsb = jsonObject.optJSONObject("result");
                    JSONArray jsonArray = jsb.optJSONArray("data");
                    Log.d(TAG, "onResponse: "+jsonArray);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        try {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            Map<String, String> map = new HashMap<>();
                            map.put("id", jsonObject1.optString("id"));
                            map.put("title", jsonObject1.optString("title"));
                            map.put("tags", jsonObject1.optString("tags"));
                            JSONArray jar = jsonObject1.getJSONArray("albums");
                            map.put("albums", jar.getString(0));
                            list.add(map);
                            Log.d(TAG, "onResponse: " + list.size());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    Log.d(TAG, "onResponse: " + list.size());
                    adapter.notifyDataSetChanged();
                }else {
                    Toast.makeText(getActivity(), "请刷新重试", Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "wlcw", Toast.LENGTH_SHORT).show();
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    class MyAdapter extends BaseAdapter{
        List<Map> list;

        public MyAdapter(List<Map> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_list_main,parent,false);
            final ImageView imageView = convertView.findViewById(R.id.img_albums);
            TextView t1 = convertView.findViewById(R.id.text_title);
            TextView t2 = convertView.findViewById(R.id.text_imtro);
            final Map<String,String> map = list.get(position);
            imageView.setTag(map.get("albums"));
            showImageByAsynTask(imageView,map.get("albums"));
            t1.setText(map.get("title"));
            t2.setText(map.get("tags"));
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(),InfoActivity.class);
                    intent.putExtra("id",map.get("id"));
                    startActivity(intent);
                }
            });
            return convertView;
        }

        Bitmap BitmapByNetWork(String url){
            Bitmap bitmap;
            InputStream is = null;
            try {
                URL mUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
                is = new BufferedInputStream(connection.getInputStream());
                bitmap = BitmapFactory.decodeStream(is);
                connection.disconnect();
                return bitmap;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        void showImageByAsynTask(ImageView iv,String s){
            new NewAsyncTask(iv,s).execute(s);
        }

        class NewAsyncTask extends AsyncTask<String,Void,Bitmap> {
            private ImageView imageView;
            private String mUrl;

            public NewAsyncTask(ImageView imageView, String mUrl) {
                this.imageView = imageView;
                this.mUrl = mUrl;
            }

            @Override
            protected Bitmap doInBackground(String... strings) {
                Log.d(TAG, "doInBackground: "+strings[0]);
                return BitmapByNetWork(strings[0]);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                if(imageView.getTag().equals(mUrl)){
                    imageView.setImageBitmap(bitmap);
                }
            }
        }

    }


}
